﻿using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;

// based off of
// http://dotnetaddict.dotnetdevelopersjournal.com/wp7_serialization_data.htm 
namespace Coding4Fun.Cannon.Phone
{
	[DataContract]
	public class Settings
	{
		private const string SettingsFileName = "Settings.dat";
		
		[DataMember]
		public string EndpointUrl { get; set; }

		[DataMember]
		public bool UseRcCar { get; set; }

		[DataMember]
		public bool IsInverseTilt { get; set; }

		public int PanMinimum { get; set; }
		public int PanMaximum { get; set; }
		
		public int TiltMinimum { get; set; }
		public int TiltMaximum { get; set; }

		public static Settings Load()
		{
			Settings settings = null;

			using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
			{
				using (var stream = new IsolatedStorageFileStream(SettingsFileName, FileMode.OpenOrCreate, isf))
				{
					if (stream.Length > 0)
					{
						var dcs = new DataContractSerializer(typeof(Settings));
						settings = dcs.ReadObject(stream) as Settings;
					}
				}
			}

			return settings ??
			       (new Settings{
					   UseRcCar = false,
					   IsInverseTilt = false,
					   EndpointUrl = "betty2",
				   });
		}

		public void Save()
		{
			using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
			{
				using (var stream = new IsolatedStorageFileStream(SettingsFileName, FileMode.Create, isf))
				{
					var dcs = new DataContractSerializer(typeof(Settings));
					dcs.WriteObject(stream, this);
				}
			}
		}
	}
}
